//
//  HOTFreeListViewController.m
//  Genpara
//
//  Created by AndyChang.zhang on 14-10-9.
//  Copyright (c) 2014年 zhangchh. All rights reserved.
//

#import "HOTGenbakakikomiListViewController.h"
#import "HOTFreeListCell.h"
#import "HOTPopupView.h"
#import "HOTGenbaInfoViewController.h"

@interface HOTGenbakakikomiListViewController () <HOTFreeListCellDelegate, UISearchBarDelegate> {
    
    UIView *mengBan;
    NSInteger _pageNo;
}
@property(nonatomic,copy)NSString *freeWord;
@property(nonatomic,strong)NSMutableArray *dataList;
@end

@implementation HOTGenbakakikomiListViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setNaviTitle:@"現場一覧"];
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg_genba"]];
    
    
    //添加导航右侧搜索按钮
    [self addRightBtnTarget:self
                     action:@selector(searchBtnClicked:)
                      image:[UIImage imageNamed:@"btn_search_off"]
                     hImage:[UIImage imageNamed:@"btn_search_on"]];
    
    _tableView.showFooter = YES;
    _tableView.showHeader = YES;
    
    //__unsafe_unretained HOTFreeListViewController *tempObj = self;
    _tableView.headerView.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        
        _pageNo = 1;
    };
    
    //_searchBarView.frame = CGRectMake(0, -_searchBarView.frame.size.height, self.view.frame.size.width, _searchBarView.frame.size.height);
    
    mengBan = [[UIView alloc] initWithFrame:CGRectMake(0, _searchBarView.frame.size.height, self.view.frame.size.width, self.view.frame.size.height)];
    mengBan.backgroundColor = [UIColor blackColor];
    
    //[self.view addSubview:_searchBarView];
    _searchBarView.delegate = self;
    _tableView.footerView.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        
        _pageNo ++;
        [self requestDataFromNet];

    };
    
    self.dataList = [NSMutableArray array];
    
    _pageNo =1;
    [self requestDataFromNet];
}

#pragma mark - UItableView DataSource
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *cellId = @"cellID";
    HOTFreeListCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    
    if (cell == nil) {
        
        UINib *nib = [UINib nibWithNibName:XIB(@"HOTFreeListCell") bundle:nil];
        [tableView registerNib:nib forCellReuseIdentifier:cellId];
        
        cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    }
    NSDictionary *dic = [self.dataList objectAtIndex:indexPath.row];
    cell.indexPath = indexPath;
    cell.delegate = self;
    NSString *jobName = [self.userInfo jobNameWithId:[dic objectForKey:@"job_id"] jobName:[dic objectForKey:@"job_name"]];
    NSString *cityName = [self.userInfo cityNameWithId:[dic objectForKey:@"city_id"]];
    cell.addrAndJobLabel.text = [NSString stringWithFormat:@"【%@】%@", cityName, jobName];
    cell.dateTimeLabel.text = [HOTUtils getString:[dic objectForKey:@"publish_time"]];
    cell.nickNameLab.text = [HOTUtils getString:[dic objectForKey:@"user_name"]];
    cell.nickNameLab.user_id = [HOTUtils getString:[dic objectForKey:@"user_id"]];
    cell.nickNameLab.targetVcClass = [self class];
    cell.contentLabel.text = [HOTUtils getString:[dic objectForKey:@"workp_detail"]];
    
    return cell;
}

-(void)requestDataFromNet {
    
    [self showLoading];
    
    NSDictionary *parameters = @{REQ_KEY_USER_TOKEN:self.userInfo.token,
                                 REQ_KEY_QUERY_WORD:[HOTUtils getString:self.freeWord],
                                 REQ_KEY_P_NUM:@(_pageNo),
                                 REQ_KEY_P_SIZE:kPageCnt};
    
    __unsafe_unretained HOTGenbakakikomiListViewController *tempObj = self;
    [self requestWithURL:HOT_URL_FREE_SCENE Parameters:parameters success:^(NSInteger result, NSArray * dataArr) {
        
        [tempObj loadingSuccess];
        [_tableView.headerView endRefreshing];
        [_tableView.footerView endRefreshing];
        if (dataArr.count == 0) {
            
            if (_pageNo == 1) {
                
                [tempObj.dataList removeAllObjects];
                [_tableView reloadData];
                [self alertNoDataMessage:^{
                    //[tempObj.navigationController popViewControllerAnimated:YES];
                }];
            } else {
                [self alertNoDataAgainMessage:nil];
            }
            
            
            return;
        }
        
        if (_pageNo == 1) {
            [tempObj.dataList removeAllObjects];
        }
        [tempObj.dataList addObjectsFromArray:dataArr];
        
        [_tableView reloadData];
        
    } failure:^(NSError *error, NSString *errMsg) {
        
        [tempObj loadingSuccess];
        [_tableView.headerView endRefreshing];
        [_tableView.footerView endRefreshing];
        if ([tempObj checkErrResult:error errMsg:errMsg]) {
            return ;
        }
        if (errMsg.length > 0) {
            
            ZZZPopupView *popupView = [[ZZZPopupView alloc] initWithTitle:ALERT_TITLE
                                                                  message:errMsg
                                                                 delegate:nil
                                                        cancelButtonTitle:nil
                                                         otherButtonTitle:ALERT_BTN_OK];
            
            [popupView showInWindow];
        }
    }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.dataList.count;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *cellId = @"cellID";
    HOTFreeListCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    
    if (cell == nil) {
        
        UINib *nib = [UINib nibWithNibName:XIB(@"HOTFreeListCell") bundle:nil];
        [tableView registerNib:nib forCellReuseIdentifier:cellId];
        
        cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    }
    //[cell.nickNameLab setTitle:@"マージ" forState:UIControlStateNormal];
    
    [cell setNeedsDisplay];
    [cell setNeedsUpdateConstraints];
    [cell.contentView setNeedsUpdateConstraints];
    [cell.contentView setNeedsDisplay];
    
    float cellH = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
    return cellH +1;
}

#pragma mark - UITableView Delegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

-(void)detailBtnClickedAtIndexPath:(NSIndexPath *)indexPath {
    
//    HOTPopupView *popupView = [[HOTPopupView alloc] initWithTitle:@"確認" message:@"详细を見るには600現使用します。\n よろしいですか？"];
//    
//    __unsafe_unretained HOTGenbakakikomiListViewController *unretainObj = self;
//    popupView.popBtnClickedBlock = ^(HOTPopBtnType btnType) {
//      
//        if (btnType == HOTPopOKBtn) {
//            
//            NSDictionary *dic = [_dataList objectAtIndex:indexPath.row];
//            HOTGenbaInfoViewController *flvc = [[HOTGenbaInfoViewController alloc] initWithNibName:@"HOTGenbaInfoViewController" bundle:nil genbaInfo:dic];
//            
//            [unretainObj.navigationController pushViewController:flvc animated:YES];
//        }
//    };
//    [popupView showInWindow];
    
    NSDictionary *dic = [_dataList objectAtIndex:indexPath.row];
    HOTGenbaInfoViewController *flvc = [[HOTGenbaInfoViewController alloc] initWithNibName:@"HOTGenbaInfoViewController" bundle:nil genbaInfo:dic];
    
    [self.navigationController pushViewController:flvc animated:YES];
}

#pragma mark - UISearchBar Delegate
-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    
    [_searchBarView setShowsCancelButton:NO animated:YES];
    [self hiddenMengban];
}

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    
    //按关键字搜索
    self.freeWord = _searchBarView.text;
    [self searchBtnClicked:nil];
    
}

-(BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    
    [self showMengban];
    
    return YES;
}

#pragma mark - 私有函数
-(void)searchBtnClicked:(id)sender {
    
    if ([_searchBarView isFirstResponder]) {
        
        [_searchBarView setShowsCancelButton:NO animated:YES];
        [self hiddenMengban];
    }
    self.freeWord = _searchBarView.text;
    //[self requestDataFromNet];
}

-(void)showMengban {
    
    //[_searchBarView becomeFirstResponder];
    mengBan.alpha = 0;
    [self.view addSubview:mengBan];
    [_searchBarView setShowsCancelButton:YES animated:YES];
    [UIView animateWithDuration:0.3 animations:^{

        mengBan.alpha = 0.7f;
        
    } completion:^(BOOL finished) {

    }];
}

-(void)hiddenMengban {
    
    [_searchBarView resignFirstResponder];
    [UIView animateWithDuration:0.3 animations:^{
        
        mengBan.alpha = 0.f;
        
    } completion:^(BOOL finished) {
        
        if (finished) {
            [mengBan removeFromSuperview];
        }
    }];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
